package com.character.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.character.entity.User;
import com.character.service.MenuService;
import com.character.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    /**
     * @create by: cc
     * @description: 授权功能
     * @create time: 2021/12/5 15:05
     * @param principalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //此处连接数据库获取perms字段
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Set<String> perms = menuService.getAllPermsByLoginName(user.getLoginName());
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }
    /**
     * @create by:cc
     * @description: 认证功能
     * @create time: 2021/12/5 15:16
     * @param authenticationToken
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取令牌对象
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        //第一步校验用户是否存在
        String loginName = usernamePasswordToken.getUsername();
        QueryWrapper<User> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("login_name",loginName);
        User user = userService.getOne(queryWrapper);
        if(null==user){
            return null;
        }
        //第二步校验密码是否正确
        //获取密码的密文
        String password = user.getPassword();
        //获取密码的盐值
        String salt = user.getSalt();
        ByteSource byteSource = ByteSource.Util.bytes(salt);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password, byteSource, getName());
        return simpleAuthenticationInfo;
    }
}
